package com.zk.iotgateway.Config;

import com.zk.iotgateway.constant.Loggers;
import com.zk.iotgateway.manager.GlobalManager;
import com.zk.iotgateway.domain.param.IotConfigDO;
import com.zk.iotgateway.domain.param.IotDispatchDO;
import com.zk.iotgateway.rabbitmq.PublisherConfig;
import com.zk.iotgateway.service.IotConfigService;
import com.zk.iotgateway.service.IotDispatchService;
import com.zk.iotgateway.util.ServerLogUtils;
import org.slf4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * ${DESCRIPTION}
 *
 * @author:mn.m
 * @create 2019-05-07 上午 10:53
 **/
@Component
public class IotInitRunner implements CommandLineRunner {

    private Logger log = Loggers.initLogger;

    @Autowired
    private IotConfigService iotConfigService;
    @Autowired
    private IotDispatchService iotDispatchService;

    @Override
    public void run(String... args) throws Exception {

        List<IotConfigDO> list= iotConfigService.findAllValid();
        if (list!=null&&!list.isEmpty()){
            log.info("--------------开始初始化------------------");
            ServerLogUtils.writeDefaultStatusLog(" --开始初始化mq--");
            for (IotConfigDO item:list){
                List<IotDispatchDO> mqlist=iotDispatchService.findValidByPort(item.getPort());
                Map<String, PublisherConfig> mqpushlist=new HashMap<>();
                for (IotDispatchDO ditem:mqlist){
                    PublisherConfig publisherConfig=new PublisherConfig();
                    publisherConfig.initConfig(ditem);
                    mqpushlist.put(ditem.getId(),publisherConfig);
                }
                GlobalManager.MQMANAGER.put(item.getPort(),mqpushlist);
            }
            ServerLogUtils.writeDefaultStatusLog(" -----------mq初始化结束----------------");
            ServerLogUtils.writeDefaultStatusLog(" ------------网关初始化开始---------");
            for (IotConfigDO item:list){
                iotConfigService.establish(item);
            }
            log.info("------------网关初始化结束---------");
        }
    }
}
